<?php

/**
 * booking actions.
 *
 * @package    playcafebookings
 * @subpackage booking
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class bookingActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->form = new BookingForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new BookingForm();

    $this->processForm($request, $this->form);

    // If the save is successful we won't get to this point - processForm() does a redirect
    
    // Go back to the original page to fix errors
    $this->setTemplate('index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $customValues = $request->getParameter('custom');
    
    $form->bindWithCustomValues($request->getParameter($form->getName()), $request->getFiles($form->getName()), $customValues);
    if ($form->isValid())
    {
      $booking = $form->save();

      $this->redirect('booking/confirm?id='.$booking->getId());
    }
  }
  
  public function executeConfirm(sfWebRequest $request) {
    $this->id = $request->getParameter('id');
  }
  
  public function executeCheckDate(sfWebRequest $request) {
    $date = $request->getParameter('date');
    
    $this->forward404Unless($date);
    
    $startDate = date('Y-m-d 00:00:00', strtotime($date));
    $endDate = date('Y-m-d 23:59:59', strtotime($date));
    
    $count = Doctrine_Core::getTable('Booking')
        ->createQuery('b')
        ->where('b.booking_datetime >= \'' . $startDate . '\'')
        ->andWhere('b.booking_datetime <= \'' . $endDate . '\'')
        ->count();
    
    $available = ($count >= 5 ? false : true);
    
    $this->getResponse()->setContentType('application/json');
    return $this->renderText(json_encode(array('available' => $available)));
  }
}
